package com.hu.controller;

import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.hu.config.comment.ResponseResult;
import com.hu.config.permission.Role;
import com.hu.config.permission.Roles;
import com.hu.dal.pojo.User;
import com.hu.service.UserService;
import com.hu.uitl.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private UserService userService;

    @Roles(type = Role.SUPUSER)
    @RequestMapping(value = "listUser", method = RequestMethod.GET)
    public ResponseResult listUser(@RequestParam(required = false, defaultValue = "1") int page,
                                   @RequestParam(required = false, defaultValue = "10") int pageSize) {
        return userService.getAll(page, pageSize);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public ResponseResult getById(@PathVariable("id") int id) {
        System.out.println("获取"+id);
        return userService.getById(id);
    }

    @RequestMapping(value = "deleteUser/{id}", method = RequestMethod.DELETE)
    public ResponseResult deleteUser(@PathVariable("id") int id) {
        System.out.println("删除"+id);
        return userService.delete(id);
    }

    @RequestMapping(value = "updateUser/{id}", method = RequestMethod.PUT)
    public ResponseResult updateUser(@Valid User users) {
        System.out.println("修改");
        return userService.update(users);
    }

    @RequestMapping(value = "addUser", method = RequestMethod.POST)
    public ResponseResult addUser(@Valid User users) {
        System.out.println(users.getPassword()+"=======");
        return userService.insert(users);
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public ResponseResult login(@Valid User users) {
//验证
        if(users.getName().equals("admin")&&users.getPassword().equals("123")){
            //假装从数据库查出来的数据
            User u = new User();
            u.setId(1);
            u.setName("admin");
            u.setRole(1);

            SimplePropertyPreFilter filter = new SimplePropertyPreFilter(User.class, "password");
//生成token
            Map m = new HashMap<>();
            m.put("username", "admin");
            m.put("role", 1);
            m.put("id",1);
            String token=new JwtUtils().createToken(m);
//返回信息
            m.clear();
            m.put("token",token);
            m.put("name","admin");

            return ResponseResult.success("ok",m);
               }
               return ResponseResult.unauthorized("错误");

    }
}
